<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Http\Requests\RegisterRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): Response
    {
        return Inertia::render('Auth/Register');
    }

    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(RegisterRequest $request): RedirectResponse
    {
        // 判断是邮箱还是手机号
        $isEmail = filter_var($request->email, FILTER_VALIDATE_EMAIL);
        
        $userData = [
            'name' => $request->name,
            'password' => Hash::make($request->password),
        ];
        
        if ($isEmail) {
            // 邮箱注册
            $userData['email'] = $request->email;
            $userData['phone'] = null;
        } else {
            // 手机号注册
            $userData['email'] = null;
            $userData['phone'] = $request->email;
        }
        
        $user = User::create($userData);

        event(new Registered($user));

        Auth::login($user);

        return redirect(RouteServiceProvider::HOME);
    }
}
